﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CubicFWNet.Application.SystemManager;
using CubicFWNet.Common;
using CubicFWNet.Data.Models;
using CubicFWNet.Data.ViewModal;
using CubicFWNet.Mvc.Models;
using PagedList;
namespace CubicFWNet.Mvc.Controllers
{
    public class TechnologyController : ControllerBase
    {
        private TechnologyApp _technologyApp;
        private OrderProductApp _orderProductApp;
        private OperateRecordApp _operateRecordApp;
        private ProductApp _productApp;
        private CreateNewNumberApp _createNewNumberApp;

        public TechnologyController()
        {
            _technologyApp = new TechnologyApp();
            _orderProductApp = new OrderProductApp();
            _operateRecordApp = new OperateRecordApp();
            _productApp = new ProductApp();
            _createNewNumberApp = new CreateNewNumberApp();
        }

        public ActionResult Service(int page = 1, int type = 1, string productName = "", string productNum = "")
        {
            ViewBag.ProductName = productName.Trim();
            ViewBag.ProductNum = productNum.Trim();
            ViewBag.Type = type;

            IPagedList<Product> productList = _productApp.GetFuckList(type, 1, productName.Trim(), productNum.Trim()).ToPagedList(page, 10);
            return View(productList);
        }

        public ActionResult ServiceBack(int page = 1, int type = 1, string productName = "", string productNum = "")
        {
            ViewBag.ProductName = productName.Trim();
            ViewBag.ProductNum = productNum.Trim();
            ViewBag.Type = type;

            IPagedList<Product> productList = _productApp.GetListBack(type, 1, productName.Trim(), productNum.Trim()).ToPagedList(page, 10);
            return View(productList);
        }

        public ActionResult ServiceItem(int page = 1, string pId = "", string productName = "", string productNum = "")
        {
            ViewBag.ProductName = productName.Trim();
            ViewBag.ProductNum = productNum.Trim();
            Guid proId = Guid.Empty;
            if (!string.IsNullOrEmpty(pId) && Validate.IsGuidByParse(pId))
            {
                proId = Guid.Parse(pId);
            }
            ViewBag.pId = proId;
            IPagedList<ProductTechnologyView> productList = _technologyApp.GetTechnologyManageList(proId, productName.Trim(), productNum.Trim()).ToPagedList(page, 10);
            return View(productList);
        }


        [HttpPost]
        [HandlerAjaxOnly]
        public string GetLevelList(Guid selectVal)
        {
            var levelList = _technologyApp.GetListTechType(selectVal, "").ToList();
            return levelList.ToJson();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pId">产品id</param>
        /// <param name="tmId">产品关联原材料id</param>
        /// <returns></returns>
        public ActionResult CheckService(Guid pId)
        {
            List<Product> proList = new List<Product>();
            Product pro = _technologyApp.GetSingleProduct(pId);
            TechnologyManageView tmweb = _technologyApp.GetTechnologyManageSingle(pId);
            Guid tmId = Guid.Empty;
            List<TechType> levelList = null;
            string isAdd = "0";

            if (tmweb == null)
            {
                isAdd = "1";

            }
            else //说明是编辑
            {
                if (!string.IsNullOrEmpty(tmweb.MaterialIdsData))
                {
                    List<Guid> list = Common.Json.ToObject<List<Guid>>(tmweb.MaterialIdsData);
                    foreach (var item in list)
                    {
                        Product itemPro = _technologyApp.GetSingleProduct(item);
                        proList.Add(itemPro);
                    }
                }
                levelList = _technologyApp.GetListTechType(tmweb.EquipmentType, "").ToList();

            }
            ViewBag.LevelList = levelList;//类别集合
            ViewBag.prosList = proList;

            //List<Guid> list = _technologyApp.ContainsTmId(pId);
            //if (list.Count > 0)
            //{
            //    list.Remove(tmId);
            //}


            //ViewBag.ProductList = _productApp.GetList(2, 1, "", "");//.Where(a => !list.Contains(a.Id));//获得主料(去除已有的原材料)
            //ViewBag.MaterialList = _productApp.GetList(3, 1, "", "");//获取辅料
            //IEnumerable<Equipment> listEquipments = _technologyApp.GetListEquipment("");

            //ViewBag.TechnologyManageView = tmweb;
            //ViewBag.Product = pro;
            //ViewBag.ProductId = pId;
            //ViewBag.IsAdd = isAdd;
            //ViewBag.ListEquipments = listEquipments;

            return View(new Technology());
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public string AddOrUpdateService(TechnologyManage tm, ProductView pro, string itemIds, string isAdd, int type)
        {
            //List<Guid> list = Common.Json.ToObject<List<Guid>>(itemIds);
            //编辑
            if (isAdd == "0")
            {
                tm.MaterialIdsData = itemIds;
                _technologyApp.UpdateTechnologyManage(tm);
            }
            //添加
            if (isAdd == "1")
            {
                tm.Id = Guid.NewGuid();
                tm.CreateTime = DateTime.Now;
                tm.MaterialIdsData = itemIds;
                _technologyApp.InsertTechnologyManage(tm);
            }

            var product = _productApp.GetInfo(pro.ProductID);
            if (product!=null)
            {
                product.SizeWidth = pro.SizeWidth;
                product.SizeLenth = pro.SizeLenth;
                //product.WorkType = pro.WorkType;
                _productApp.Update(product);
            }

            return Result.ToJson();
        }

        public ActionResult Index(int page = 1, string productName = "", string productNum = "", string beginTime = "", string endTime = "")
        {
            ViewBag.ProductName = productName.Trim();
            ViewBag.ProductNum = productNum.Trim();
            DateTime _beginTime = DateTime.Parse("2000-01-01 10:10:10");
            DateTime _endTime = DateTime.Now.Date.AddDays(1);
            ViewBag.beginTime = "";
            ViewBag.endTime = "";
            if (!string.IsNullOrEmpty(beginTime) && Validate.IsDate(beginTime))
            {
                _beginTime = DateTime.Parse(beginTime.Trim());
                ViewBag.beginTime = beginTime.Trim();
            }
            if (!string.IsNullOrEmpty(endTime) && Validate.IsDate(endTime))
            {
                _endTime = DateTime.Parse(endTime.Trim());
                ViewBag.endTime = endTime.Trim();
            }

            IPagedList<ProductTechnologyView> tecjList = _technologyApp.GetList(-1, productName.Trim(), productNum.Trim(), "", _beginTime, _endTime).ToPagedList(page, 10);
            return View(tecjList);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="tId">工艺id</param>
        /// <param name="pId">产品id</param>
        /// <param name="productName"></param>
        /// <param name="productNum"></param>
        /// <returns></returns>
        public ActionResult IndexItem(int page = 1, string tId = "", string pId = "", string productName = "", string productNum = "", string pname = "")
        {
            ViewBag.ProductName = productName.Trim();
            ViewBag.ProductNum = productNum.Trim();
            Guid proId = Guid.Empty;
            Guid techId = Guid.Empty;

            if (!string.IsNullOrEmpty(tId) && Validate.IsGuidByParse(tId))
            {
                techId = Guid.Parse(tId);
                Technology t = _technologyApp.GetSingleTechnology(techId);
                OrderProduct op = _orderProductApp.GetSingleOrderProduct(t.OrderProductId);
                Product p = _technologyApp.GetSingleProduct(op.ProductId.Value);
                pname = p.Name;
            }
            if (!string.IsNullOrEmpty(pId) && Validate.IsGuidByParse(pId))
            {
                proId = Guid.Parse(pId);
            }
            ViewBag.tId = techId;
            ViewBag.pId = proId;
            ViewBag.Pname = pname;
            IPagedList<ProductTechnologyView> tecjList = _technologyApp.GetListItem(productName.Trim(), productNum.Trim(), techId).ToPagedList(page, 10);
            foreach (var item in tecjList)
            {
                int a = _technologyApp.IsCheckMateria(item.Id, item.ProductId);
                if (a != -1)
                {
                    item.Status = a;
                }
                else
                {
                    item.Status = -1;
                }
            }
            return View(tecjList);
        }

        public ActionResult Query(int page = 1, string productName = "", string productNum = "", string technologyNum = "", string beginTime = "", string endTime = "")
        {
            ViewBag.ProductName = productName.Trim();
            ViewBag.ProductNum = productNum.Trim();
            ViewBag.TechnologyNum = technologyNum.Trim();
            DateTime _beginTime = DateTime.Parse("2000-01-01 10:10:10");
            DateTime _endTime = DateTime.Now.Date.AddDays(1);
            ViewBag.beginTime = "";
            ViewBag.endTime = "";
            if (!string.IsNullOrEmpty(beginTime) && Validate.IsDate(beginTime))
            {
                _beginTime = DateTime.Parse(beginTime.Trim());
                ViewBag.beginTime = beginTime.Trim();
            }
            if (!string.IsNullOrEmpty(endTime) && Validate.IsDate(endTime))
            {
                _endTime = DateTime.Parse(endTime.Trim());
                ViewBag.endTime = endTime.Trim();
            }
            IPagedList<ProductTechnologyView> tecjList = _technologyApp.GetList(1, productName.Trim(), productNum.Trim(), technologyNum.Trim(), _beginTime, _endTime).ToPagedList(page, 10);
            return View(tecjList);
        }

        public ActionResult QueryItem(int page = 1, string tId = "", string pId = "", string productName = "", string productNum = "", string pname = "")
        {
            ViewBag.ProductName = productName.Trim();
            ViewBag.ProductNum = productNum.Trim();
            Guid proId = Guid.Empty;
            Guid techId = Guid.Empty;

            if (!string.IsNullOrEmpty(tId) && Validate.IsGuidByParse(tId))
            {
                techId = Guid.Parse(tId);
                Technology t = _technologyApp.GetSingleTechnology(techId);
                OrderProduct op = _orderProductApp.GetSingleOrderProduct(t.OrderProductId);
                Product p = _technologyApp.GetSingleProduct(op.ProductId.Value);
                pname = p.Name;
            }
            if (!string.IsNullOrEmpty(pId) && Validate.IsGuidByParse(pId))
            {
                proId = Guid.Parse(pId);
            }
            ViewBag.tId = techId;
            ViewBag.pId = proId;
            ViewBag.Pname = pname;
            IPagedList<ProductTechnologyView> tecjList = _technologyApp.GetListItem(productName.Trim(), productNum.Trim(), techId).ToPagedList(page, 10);
            foreach (var item in tecjList)
            {
                int a = _technologyApp.IsCheckMateria(item.Id, item.ProductId);
                if (a != -1)
                {
                    item.Status = a;
                }
                else
                {
                    item.Status = -1;
                }
            }
            return View(tecjList);
        }

        public ActionResult Check(Guid tId)
        {
            Technology t = _technologyApp.GetSingleTechnology(tId);
            string operationName = operatorModel.FamilyName;

            OrderProduct op = _orderProductApp.GetSingleOrderProduct(t.OrderProductId);
            ViewBag.OrderProduct = op;

            //Product p = _technologyApp.GetSingleProduct(mId);//原材料
            //ViewBag.Product = p;
            if (op.ProductId != null)
            {
                //TechnologyManage tm = _technologyApp.GetTechnologyManageSingle2(op.ProductId.Value, mId);
                Product pro = _technologyApp.GetSingleProduct(op.ProductId.Value);
                TechnologyManageView tmweb = _technologyApp.GetTechnologyManageSingle(pro.Id);
                Product material = _technologyApp.GetSingleProduct(tmweb.MaterialId);
                Equipment equipment = _technologyApp.GetSingleEquipment(tmweb.EquipmentType);
                TechType techType = _technologyApp.GetSingleTechType(equipment.Id, tmweb.TechType);
                /*GradeMaintenance gm = _technologyApp.GetSingleGradeMaintenance(tmweb.TechType, 1);*/

                List<Product> listPro = new List<Product>();
                if (!string.IsNullOrEmpty(tmweb.MaterialIdsData))
                {
                    List<Guid> list = Common.Json.ToObject<List<Guid>>(tmweb.MaterialIdsData);
                    foreach (var item in list)
                    {
                        Product itemPro = _technologyApp.GetSingleProduct(item);
                        listPro.Add(itemPro);
                    }
                }

                ViewBag.listPro = listPro;
                ViewBag.TechnologyManage = tmweb;
                //ViewBag.GradeMaintenance = gm;
                ViewBag.Product = pro;
                ViewBag.Material = material;
                ViewBag.Equipment = equipment;
                ViewBag.TechType = techType;
                //ViewBag.MaterialId = tmweb.MaterialId;//原材料Id
            }

            #region 生成订单号
            string shortName = operatorModel.FamilyName;
            string shortTime = GenerateId.GenerateyyyyMm();
            Technology lastwebObj = _createNewNumberApp.GetLasTechnology(shortName + "-" + shortTime);
            int lastNum = 1;
            if (lastwebObj != null && lastwebObj.Number.Split('-').Length == 3 && Validate.IsIntByParse(lastwebObj.Number.Split('-')[2]))
            {
                lastNum = Convert.ToInt32(lastwebObj.Number.Split('-')[2]) + 1;
            }
            string newNumber = shortName + "-" + GenerateId.GenerateOrderNumberBack() + "-" + lastNum.ToString().PadLeft(3, '0');//生成采购编号
            #endregion

            ViewBag.Number = newNumber;//工艺编号
            ViewBag.OperationName = operationName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间

            return View(t);
        }

        /// <summary>
        /// 判断该产品是否维护了工艺
        /// </summary>
        /// <param name="tId"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        public string VerifyTechnology(Guid tId)
        {
            Result.Status = "2";
            Technology t = _technologyApp.GetSingleTechnology(tId);
            OrderProduct op = _orderProductApp.GetSingleOrderProduct(t.OrderProductId);
            if (op.ProductId != null)
            {
                Product pro = _technologyApp.GetSingleProduct(op.ProductId.Value);
                TechnologyManageView tmweb = _technologyApp.GetTechnologyManageSingle(pro.Id);
                if (tmweb != null && tmweb.MaterialId != Guid.Empty)
                {
                    Result.Status = "1";
                }
            }
            return Result.ToJson();
        }

        /// <summary>
        /// 获得所有原材料
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPermissionTree()
        {
            IEnumerable<Product> materials = _technologyApp.GetListMaterials(2);
            var treeList = new List<TreeViewModel>();
            TreeViewModel tre = new TreeViewModel()
            {
                id = "1",
                text = "原材料",
                value = "1",
                parentId = "",
                isexpand = true,
                complete = true,
                showcheck = false,
                hasChildren = true,
                img = "",
            };
            treeList.Add(tre);
            foreach (Product item in materials)
            {
                TreeViewModel tree = new TreeViewModel();
                tree.id = item.Id.ToString();
                tree.text = item.Name;
                tree.value = item.Id.ToString();
                tree.parentId = "1";
                tree.isexpand = true;
                tree.complete = true;
                tree.showcheck = true;
                tree.checkstate = 0;
                tree.hasChildren = true;
                tree.img = "";
                treeList.Add(tree);
            }
            return Content(treeList.TreeViewJson());
        }

        public ActionResult QueryInfo(Guid tId)
        {
            Technology t = _technologyApp.GetSingleTechnology(tId);
            //TechnologyItem tItem = _technologyApp.GetSingleTechnologyItem(tId, mId);

            if (t != null)
            {
                OrderProduct op = _orderProductApp.GetSingleOrderProduct(t.OrderProductId);
                ViewBag.OrderProduct = op;
                if (op.ProductId != null)
                {
                    Product pro = _technologyApp.GetSingleProduct(op.ProductId.Value);
                    TechnologyManageView tmweb = _technologyApp.GetTechnologyManageSingle(pro.Id);
                    Product material = _technologyApp.GetSingleProduct(tmweb.MaterialId);
                    Equipment equipment = _technologyApp.GetSingleEquipment(tmweb.EquipmentType);
                    TechType techType = _technologyApp.GetSingleTechType(equipment.Id, tmweb.TechType);
                    List<ProductTechnologyView> technologyItem = _technologyApp.GetTechnologyItems(t.Id);

                    ViewBag.TechnologyItemList = technologyItem;
                    ViewBag.TechnologyManage = tmweb;
                    ViewBag.Product = pro;
                    ViewBag.Material = material;
                    ViewBag.Equipment = equipment;
                    ViewBag.TechType = techType;
                }
            }

            return View(t);
        }

        public ActionResult TechnologyInfo(Guid tId)
        {
            Technology t = _technologyApp.GetSingleTechnology(tId);
            if (t == null)
            {
                OrderProduct op = _orderProductApp.GetSingleOrderProduct(tId);
                if (op.PrimaryID != null)
                {
                    op = _orderProductApp.GetSingleOrderProduct(op.PrimaryID.Value);
                }
                else
                {
                    op = _orderProductApp.GetSingleOrderProduct(tId);
                }
                t = _technologyApp.GetSingleTechnologyById(op.Id);
            }
            //TechnologyItem tItem = _technologyApp.GetSingleTechnologyItem(tId, mId);

            if (t != null)
            {
                OrderProduct op = _orderProductApp.GetSingleOrderProduct(t.OrderProductId);
                ViewBag.OrderProduct = op;
                if (op.ProductId != null)
                {
                    Product pro = _technologyApp.GetSingleProduct(op.ProductId.Value);
                    TechnologyManageView tmweb = _technologyApp.GetTechnologyManageSingle(pro.Id);
                    Product material = _technologyApp.GetSingleProduct(tmweb.MaterialId);
                    Equipment equipment = _technologyApp.GetSingleEquipment(tmweb.EquipmentType);
                    TechType techType = _technologyApp.GetSingleTechType(equipment.Id, tmweb.TechType);
                    List<ProductTechnologyView> technologyItem = _technologyApp.GetTechnologyItems(t.Id);

                    ViewBag.TechnologyItemList = technologyItem;
                    ViewBag.TechnologyManage = tmweb;
                    ViewBag.Product = pro;
                    ViewBag.Material = material;
                    ViewBag.Equipment = equipment;
                    ViewBag.TechType = techType;
                }
            }

            return View(t);
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public string Add(Technology technology, List<TechnologyItem> technologyItemList, Guid productId, Guid orderId, int type)
        {
            DateTime nowTime = DateTime.Now;

            if (technologyItemList != null)
            {
                foreach (var item in technologyItemList)
                {
                    item.Id = Guid.NewGuid();
                    item.TechnologyId = technology.Id;
                    item.CreateTime = nowTime;
                    item.CreatorId = operatorModel.UserId;
                    item.CreatorName = operatorModel.FamilyName;
                    item.Status = 1;
                    _technologyApp.AddOrUpdateTechnologyItem(item);//添加工艺子表
                }
            }

            technology.CreatorID = operatorModel.UserId;
            technology.CreatorName = operatorModel.FamilyName;
            technology.CreateTime = nowTime;
            technology.Status = 1;

            //return Result.ToJson();

            _technologyApp.AddOrUpdate(technology);//修改工艺表

            OrderProduct op = _orderProductApp.GetSingleOrderProduct(technology.OrderProductId);//根据工艺订单id查找关系表对应的OrderId
            if (null != op)
            {
                int count = _orderProductApp.GetCheckTOrderProductByOrderId(op.OrderId.Value);//如果订单旗下所有工艺都审核完毕才修改订单状态
                if (count == 0)
                {
                    //Order p = new Order();
                    //p.Id = orderId;
                    //p.Status = 3;
                    _operateRecordApp.UpdateOrderStateById(orderId, 3);//更改订单Status=3
                }
                op.Progress = 2;
                _orderProductApp.Update(op);
            }

            OperateRecord o = new OperateRecord();
            o.ItemId = technology.Id;
            o.TypeId = 3;
            o.EndTime = nowTime;
            o.CreatorId = operatorModel.UserId;
            o.CreatorName = operatorModel.FamilyName;
            _operateRecordApp.UpdateOperateRecord(o);//修改本操作人员工作记录日志

            //添加原料成本核算订单
            OriginalCost oc = new OriginalCost();
            oc.Id = Guid.NewGuid();
            oc.TechnologytId = technology.Id;
            oc.ProductName = technology.ProductName;
            oc.Materials = technology.Materials;//原材料
            oc.CreateTime = nowTime;
            oc.Status = -1;//初始状态
            oc.ApplyTime = nowTime;//订单申请时间
            oc.UserId = technology.UserId;
            _technologyApp.InsertOriginalCost(oc);

            //插入给下一个工作人员添加人工记录（原料成本核算）
            OperateRecord o1 = new OperateRecord();
            o1.Id = Guid.NewGuid();
            o1.ItemId = oc.Id;//原料成本Id
            o1.TypeId = 5;
            o1.StartTime = nowTime;
            o1.EndTime = null;
            o1.CreatorId = null;
            _operateRecordApp.AddOperateRecord(o1);

            //插入关联表
            Relation r = new Relation();
            r.Id = Guid.NewGuid();
            r.TypeId = "Technology-OriginalCost";
            r.FirstId = technology.Id;
            r.SecondId = oc.Id;
            _technologyApp.InsertRelation(r);

            return Result.ToJson();
        }

        public ActionResult Equipment(int page = 1, string equipmentName = "")
        {
            ViewBag.EquipmentName = equipmentName.Trim();
            IPagedList<Equipment> eqList = _technologyApp.GetListEquipment(equipmentName.Trim()).ToPagedList(page, 10);
            return View(eqList);
        }

        public ActionResult EquipmentService(Guid eId)
        {
            Equipment web = new Equipment();
            List<TechType> listTechType = null;
            web.Id = Guid.NewGuid();
            if (eId != Guid.Empty)
            {
                web = _technologyApp.GetSingleEquipment(eId);
                listTechType = _technologyApp.GetListTechType(web.Id, "").ToList();
            }
            ViewBag.EquipmentName = web.EquipmentName;
            ViewBag.TechTypeList = listTechType;
            return View(web);
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public string AddOrUpdateTechType(TechType techType, int sign, string equipmentName, Guid eqId)
        {

            if (techType.Data != null)
            {
                List<TechType> proList = Common.Json.ToObject<List<TechType>>(techType.Data);
                if (sign == -1)
                {
                    Equipment eq = new Equipment();
                    eq.Id = Guid.NewGuid();
                    eq.EquipmentName = equipmentName;
                    _technologyApp.InsertEquipment(eq);

                    foreach (var item in proList)
                    {
                        item.EquipmentId = eq.Id;
                        _technologyApp.InsertTechType(item);
                    }
                }
                if (sign == 1)
                {
                    Equipment eq = _technologyApp.GetSingleEquipment(eqId);
                    eq.Id = eqId;
                    eq.EquipmentName = equipmentName;
                    _technologyApp.UpdateEquipment(eq);
                    foreach (var item in proList)
                    {
                        _technologyApp.UpdateTechType(item);
                    }
                }
            }

            return Result.ToJson();
        }
    }
}